package com.ys.timer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.base.TbPlatform;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.RegionEnum;
import com.ys.enume.business.TpAmazonShopEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.service.business.TpAmazonShopProductService;
import com.ys.service.log.ApiLogService;
import com.ys.util.AESUtil;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class TimerTPAmazonShopProductDaily {

	public static Map<String, Integer> THREAD_MAPASIN = new HashMap<String, Integer>() {{
		for (int i = 0; i < 20; i++) {
			put("threadAsin" + i, 0);
		}
	}};

	public static Map<String, Integer> THREAD_MAP = new HashMap<String, Integer>() {{
		for (int i = 0; i < 20; i++) {
			put("threadAsin" + i, 0);
		}
	}};

    @Autowired
    private TpAmazonShopProductService tpAmazonShopProductService;

	@Autowired
	private ApiLogService apiLogService;

	@Autowired
	private DiySqlMapper diySqlMapper;

	@Scheduled(cron = "0 30 0 * * ?  ")
	public void getAmazonShopProductReport() {
		Date nowDate;
		String nowDateStr = null;
		try {
			//每天新增所有的网上商品信息每天信息
			nowDate = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			nowDateStr = simpleDateFormat.format(nowDate);
			diySqlMapper.insertTpAmazonShopProductReportBatch(nowDateStr);
		} catch (Exception ex) {
			apiLogService.addApiLog("Amazon", "getAmazonShopProductReport", "定时新增商品数据出错，条件queryParams：" + JSON.toJSONString(nowDateStr), "500", 500, ex.getMessage());
		}
	}

	@Scheduled(cron = "0 40 0 * * ?  ")
	public void delAmazonShopProductReport() {
		//每天新增所有的网上商品信息每天信息
		diySqlMapper.delTpAmazonShopProductReport();
	}

	@Scheduled(cron = "0 0 1 * * ?  ")
	public void getAmazonShopProduct() {
		// 没有asin的商品信息获取
		try {
			Date nowDate = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String nowDateStr = simpleDateFormat.format(nowDate);
			String updateUserId = "0000";//默认为0000，手动调用时，以调用者作为用户记录
			List<Map<String, Object>> amazonShopProductList = new TpAmazonShopProduct()
					.addLeftJoin("TP_AmazonShop tas on A.ShopId = tas.id")
					.addField("tas.sellerId as sellerId")
					.addLeftJoin("TP_AmazonSeller tsell on tsell.id = tas.AmazonSellerId")//卖家管理
					.addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
					.addLeftJoin("TB_Site ts on ts.id = tas.SiteId")//站点
					.addField("ts.AmazonMarketplaceId AS marketplaceId")
					.addLeftJoin("TB_Country tc on tc.id = ts.CountryId")//国家
					.addField("tc.name AS countryName,tc.code AS countryCode")
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.Asin IS NULL" + " AND tsell.Status = 1")
					.queryMap();

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(amazonShopProductList));

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			if (amazonShopProductList != null && amazonShopProductList.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					boolean variable = true;
					while (variable) {
						for (Map.Entry<String, Integer> e : THREAD_MAPASIN.entrySet()) {
							if (e.getValue() == 1) {
								continue;
							} else if (e.getValue() == 0) {
								THREAD_MAPASIN.put(e.getKey(), 1);
//								 开启线程
								Thread t = new Thread(() -> {
									if (jsonObject.get("awsRegion") != null) {
										jsonObject.put("type",1);
										ApiResponse apiResponse = tpAmazonShopProductService.getAsinAndProductInfo(jsonObject, nowDateStr, updateUserId,encryptSecret);
										if (apiResponse.getCode() == 500){
											apiLogService.addApiLog("Amazon","GetAsinAndProductInfo","定时获取任务获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(),apiResponse.getCode(), apiResponse.getMsg());
										}
									}
									THREAD_MAPASIN.put(e.getKey(), 0);
								});
								t.start();
								Thread.sleep(1500L);
							}
							variable = false;
							break;
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Scheduled(cron = "0 30 2 * * ?  ")
	public void getRank() {
		try {
			Date nowDate = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String nowDateStr = simpleDateFormat.format(nowDate);
			List<Map<String, Object>> tpAmazonShopList = new TpAmazonShop()
					.addLeftJoin("TP_AmazonSeller tsell on tsell.id = A.AmazonSellerId")//卖家管理
					.addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
					.addLeftJoin("TB_Site ts on ts.id = A.SiteId")//站点
					.addField("ts.AmazonMarketplaceId AS marketplaceId")
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.id in (SELECT  DISTINCT ShopId FROM TP_AmazonShopProduct)" + " AND tsell.Status = 1")
					.queryMap();
			int skuListLenth = 0;
			int skuListStar = 0;
			int k;
			List<TpAmazonShopProduct> amazonShopProductList;

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonShopList));

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				//查询所有商品信息
				amazonShopProductList = new TpAmazonShopProduct()
						.where("A.Asin IS NOT NULL")
						.where("A.shopId = '" + jsonObject.get("id").toString() +"'")
						.queryList();

				k = 0;
				if (amazonShopProductList.size() != 0) {
					skuListLenth = amazonShopProductList.size();
					skuListStar = amazonShopProductList.size();
					while (skuListStar > 0) {
						//操作api
						boolean variable = true;
						while (variable) {
							for (Map.Entry<String, Integer> e : THREAD_MAPASIN.entrySet()) {
								if (e.getValue() == 1) {
									continue;
								} else if (e.getValue() == 0) {
									THREAD_MAPASIN.put(e.getKey(), 1);
//								 开启线程
									List<TpAmazonShopProduct> finaltpAmazonShopProductList = amazonShopProductList;
									int finalK = k;
									int finalSkuListLenth = skuListLenth;
									int finalSkuListStar = skuListStar;
									Thread t = new Thread(() -> {
										//获取区域对应的端点枚举，取不到直接跳转过
										if (jsonObject.get("awsRegion") != null) {
											// 每20个获取亚马逊商品排名一系列信息
											ApiResponse apiResponse =  tpAmazonShopProductService.getRank(jsonObject, finaltpAmazonShopProductList.subList(finalK,(finalSkuListStar < 20) ? finalSkuListLenth :(finalK+20)), nowDateStr, encryptSecret);
											if (apiResponse.getCode() == 500) {
												apiLogService.addApiLog("Amazon", "GetRank", "定时获取任务获取亚马逊商品销售排名，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMsg());
											}
										}
										THREAD_MAPASIN.put(e.getKey(), 0);
									});
									t.start();
									Thread.sleep(1500L);
								}
								variable = false;
								break;
							}
						}
						if (skuListStar - 20 <= 0) {
							skuListStar = 0;
						} else {
							skuListStar = skuListStar - 20;
							k = k + 20;
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Scheduled(cron = "0 0 9 * * ?  ")
	public void getAmazonShopProductInventoryO() {
		// 定时获取亚马逊店铺商品库存信息（欧洲）
		getAmazonShopProductInventory(0);
	}

	@Scheduled(cron = "0 30 9 * * ?  ")
	public void getAmazonSalesTrafficReportO() {
		// 定时获取亚马逊店铺商品销售流量报表信息（欧洲）
		getAmazonSalesTrafficReport(0);
	}

	@Scheduled(cron = "0 0 10 * * ?  ")
	public void getAllAmazonShopProductPriceReport() {
		// 定时获取亚马逊店铺销售售价信息（欧洲）
		getAllAmazonShopProductPriceReport(0);
	}

	@Scheduled(cron = "0 30 15 * * ?  ")
	public void getAmazonShopProductInventoryB() {
		// 定时获取亚马逊店铺商品库存信息（北美）
		getAmazonShopProductInventory(1);
	}

	@Scheduled(cron = "0 0 16 * * ?  ")
	public void getAmazonSalesTrafficReportB() {
		// 定时获取亚马逊店铺商品销售流量报表信息（北美）
		getAmazonSalesTrafficReport(1);
	}

	@Scheduled(cron = "0 30 16 * * ?  ")
	public void getAllAmazonShopProductPriceReportB() {
		// 定时获取亚马逊店铺销售产品信息(北美)
		getAllAmazonShopProductPriceReport(1);
	}

	private void getAllAmazonShopProductPriceReport(int type){
		Boolean b = false;
		Boolean alx;
		try {
			do {
				alx = false;
				for (Map.Entry<String, Integer> e : THREAD_MAP.entrySet()) {
					if (e.getValue() == 1) {
						b = true;
						alx = true;
					}
				}
				if (b == true){
					Thread.sleep(1000L);
				}
			}while (alx);

			Date nowDate = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String nowDateStr = simpleDateFormat.format(nowDate);
			Date startTime = new Date();
			startTime.setHours(0);
			startTime.setMinutes(0);
			startTime.setSeconds(0);
			String startTimeStr = DateUtils.convertDateToTDate(startTime);
			Date endTime = new Date();
			endTime.setHours(23);
			endTime.setMinutes(59);
			endTime.setSeconds(59);
			String endTimeStr = DateUtils.convertDateToTDate(endTime);

			String regionName = "";
			if (type == 0){
				regionName = " AND ts.regionCode = 'EUROPE'";
			} else if (type == 1){
				regionName = " AND ts.regionCode = 'NORTH'";
			}
			List<Map<String, Object>> tpAmazonShopList = new TpAmazonShop()
					.addLeftJoin("TP_AmazonSeller tsell on tsell.id = A.AmazonSellerId")//卖家管理
					.addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
					.addLeftJoin("TB_Site ts on ts.id = A.SiteId")//站点
					.addField("ts.AmazonMarketplaceId AS marketplaceId")
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.id in (SELECT  DISTINCT ShopId FROM TP_AmazonShopProduct)" + regionName + "AND tsell.Status = 1")
					.queryMap();

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			List<TpAmazonShopProduct> amazonShopProductList;
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonShopList));
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				//查询所有商品信息
				amazonShopProductList = new TpAmazonShopProduct()
						.where("A.Asin IS NOT NULL")
						.where("A.shopId = '" + jsonObject.get("id").toString() +"'")
						.queryList();
				if (amazonShopProductList != null) {
					boolean variable = true;
					while (variable) {
						for (Map.Entry<String, Integer> e : THREAD_MAPASIN.entrySet()) {
							if (e.getValue() == 1) {
								continue;
							} else if (e.getValue() == 0) {
								THREAD_MAP.put(e.getKey(), 1);
//								 开启线程
								List<TpAmazonShopProduct> finalAmazonShopProductList = amazonShopProductList;
								Thread t = new Thread(() -> {
									//获取区域对应的端点枚举，取不到直接跳转过
									if (jsonObject.get("awsRegion") != null) {
										ApiResponse apiResponse = tpAmazonShopProductService.getAllAmazonShopProductPriceReport(jsonObject, startTimeStr, endTimeStr, nowDateStr, finalAmazonShopProductList,encryptSecret);
										if (apiResponse.getCode() == 500) {
											apiLogService.addApiLog("Amazon", "GetAmazonShopProductPriceReport", "ECP_API定时获取亚马逊店铺商品价格报表信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMsg());
										}
									}
									THREAD_MAP.put(e.getKey(), 0);
								});
								t.start();
								Thread.sleep(1000L);
							}
							variable = false;
							break;
						}
					}
				}
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void getAmazonShopProductInventory(int type){
		try {
			Date nowDate = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String nowDateStr = simpleDateFormat.format(nowDate);
			String regionName = "";
			if (type == 0){
				regionName = " AND ts.regionCode = 'EUROPE'";
			} else if (type == 1){
				regionName = " AND ts.regionCode = 'NORTH'";
			}

			List<Map<String, Object>> tpAmazonShopList = new TpAmazonShop()
					.addLeftJoin("TP_AmazonSeller tsell on tsell.id = A.AmazonSellerId")//卖家管理
					.addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
					.addLeftJoin("TB_Site ts on ts.id = A.SiteId")//站点
					.addField("ts.AmazonMarketplaceId AS marketplaceId")
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.id in (SELECT  DISTINCT ShopId FROM TP_AmazonShopProduct)" + regionName + " AND tsell.Status = 1")
					.queryMap();
			int skuListLenth = 0;
			int skuListStar = 0;
			int k;
			List<TpAmazonShopProduct> amazonShopProductList;

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonShopList));
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				//查询所有商品信息
				amazonShopProductList = new TpAmazonShopProduct()
						.where("A.Asin IS NOT NULL")
						.where("A.shopId = '" + jsonObject.get("id").toString() +"'")
						.queryList();

				k = 0;
				if (amazonShopProductList != null) {
					skuListLenth = amazonShopProductList.size();
					skuListStar = amazonShopProductList.size();
					while (skuListStar > 0) {
						//操作api
						boolean variable = true;
						while (variable) {
							for (Map.Entry<String, Integer> e : THREAD_MAP.entrySet()) {
								if (e.getValue() == 1) {
									continue;
								} else if (e.getValue() == 0) {
									THREAD_MAP.put(e.getKey(), 1);
//								 开启线程
									List<TpAmazonShopProduct> finaltpAmazonShopProductList = amazonShopProductList;
									int finalK = k;
									int finalSkuListLenth = skuListLenth;
									int finalSkuListStar = skuListStar;
									Thread t = new Thread(() -> {
										//获取区域对应的端点枚举，取不到直接跳转过
										if (jsonObject.get("awsRegion") != null) {
											ApiResponse apiResponse = tpAmazonShopProductService.getAmazonShopProductInventory(jsonObject, finaltpAmazonShopProductList.subList(finalK,(finalSkuListStar < 50) ? finalSkuListLenth :(finalK+50)), nowDateStr, encryptSecret);
											if (apiResponse.getCode() == 500) {
												apiLogService.addApiLog("Amazon", "GetAmazonShopProductInventory", "定时获取任务获取亚马逊网上商品信息，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMsg());
											}
										}
										THREAD_MAP.put(e.getKey(), 0);
									});
									t.start();
									Thread.sleep(1500L);
								}
								variable = false;
								break;
							}
						}
						if (skuListStar - 50 <= 0) {
							skuListStar = 0;
						} else {
							skuListStar = skuListStar - 50;
							k = k + 50;
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void getAmazonSalesTrafficReport(int type) {
		try {
			//获取开始时间和结束时间
			Calendar calendar = new GregorianCalendar();
			calendar.add(Calendar.DATE, -2);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String nowDateStr = simpleDateFormat.format(calendar.getTime());
			Date startTime = calendar.getTime();
			startTime.setHours(0);
			startTime.setMinutes(0);
			startTime.setSeconds(0);
			String startTimeStr = DateUtils.convertDateToTDate(startTime);
			Date endTime = calendar.getTime();
			endTime.setHours(23);
			endTime.setMinutes(59);
			endTime.setSeconds(59);
			String endTimeStr = DateUtils.convertDateToTDate(endTime);
			String regionName = "";
			if (type == 0){
				regionName = " AND ts.regionCode = 'EUROPE'";
			} else if (type == 1){
				regionName = " AND ts.regionCode = 'NORTH'";
			}
			List<Map<String, Object>> tpAmazonShopList = new TpAmazonShop()
					.addLeftJoin("TP_AmazonSeller tsell on tsell.id = A.AmazonSellerId")//卖家管理
					.addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
					.addLeftJoin("TB_Site ts on ts.id = A.SiteId")//站点
					.addField("ts.AmazonMarketplaceId AS marketplaceId")
					.addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
					.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
					.where("A.id in (SELECT  DISTINCT ShopId FROM TP_AmazonShopProduct)" + regionName + " AND tsell.Status = 1")
					.queryMap();
			List<TpAmazonShopProduct> amazonShopProductList;

			//平台
			TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
			if (tbPlatform == null){
				return;
			}
			String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonShopList));
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				//查询所有商品信息
				amazonShopProductList = new TpAmazonShopProduct()
						.where("A.Asin IS NOT NULL")
						.where("A.shopId = '" + jsonObject.get("id").toString() +"'")
						.queryList();
				if (amazonShopProductList != null) {
					boolean variable = true;
					while (variable) {
						for (Map.Entry<String, Integer> e : THREAD_MAPASIN.entrySet()) {
							if (e.getValue() == 1) {
								continue;
							} else if (e.getValue() == 0) {
								THREAD_MAPASIN.put(e.getKey(), 1);
//								 开启线程
								List<TpAmazonShopProduct> finalAmazonShopProductList = amazonShopProductList;
								Thread t = new Thread(() -> {
									//获取区域对应的端点枚举，取不到直接跳转过
									if (jsonObject.get("awsRegion") != null) {
										ApiResponse apiResponse = tpAmazonShopProductService.getAmazonSalesTrafficReport(jsonObject, startTimeStr, endTimeStr, nowDateStr, finalAmazonShopProductList,encryptSecret);
										if (apiResponse.getCode() == 500) {
											apiLogService.addApiLog("Amazon", "GetAmazonShopProductSalesTrafficReport", "定时获取任务获取亚马逊商品信息，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMsg());
										}
									}
									THREAD_MAPASIN.put(e.getKey(), 0);
								});
								t.start();
								Thread.sleep(1000L);
							}
							variable = false;
							break;
						}
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
